import { useMemberStore } from '@/stores/modules/memberStore';

const BASE_URL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net';

// 网络请求拦截器
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = `${BASE_URL}${options.url}`
    }
    options.timeout = options.timeout || 10000
    // 配置小程序端请求头标识
    options.header = { 'source-client': 'miniapp', ...options.header }
    // 添加登录token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) options.header.Authorization = token
  },
};

uni.addInterceptor('request', httpInterceptor);
uni.addInterceptor('uploadFile', httpInterceptor);

type Data<T> = {
  code: string
  msg: string
  result: T
};

// http请求工具
export const httpRequest = <T>(options: UniApp.RequestOptions) => {
  let task: UniApp.RequestTask;
  const request = new Promise<Data<T>>((resolve, reject) => {
    task = uni.request({
      ...options,
      // 成功回调
      success(response) {
        if (response.statusCode >= 200 && response.statusCode < 300) {
          // 成功
          resolve(response.data as Data<T>)
        } else if (response.statusCode === 401) {
          // 登录token过期
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(response)
        } else {
          // 其它
          uni.showToast({ icon: 'none', title: (response.data as Data<T>).msg || '请求出错！' })
          reject(response);
        }
      },
      fail(error) {
        reject(error);
      },
    })
  });
  return { request, task: task! };
};

// http文件上传工具
export const httpUpload = <T>(options: UniApp.UploadFileOption) => {
  let task = null;
  const upload = new Promise<Data<T>>((resolve, reject) => {
    task = uni.uploadFile({
      ...options,
      success(response) {
        if (response.statusCode === 200) {
          resolve(JSON.parse(response.data) as Data<T>);
        } else {
          reject(response);
        }
      },
      fail(error) {
        uni.showToast({ icon: 'none', title: '当前网络状况不佳，请稍后重试！' })
        reject(error);
      },
    });
  });
  return { upload, task };
};
